<?php
class ByteBuffer {
    private $byteArray;
    private $capacity;
    private $limit;
    private $position;
    public static function allocate($length) {
		$bytes = array();
		for($i = 0; $i< $length; $i++){
			$bytes[] = 0;
		}
        return new ByteBuffer($bytes);
    }
    public static function wrap($byteArray) {
        return new ByteBuffer($byteArray);
    }
    public function __construct($byteArray) {
        $this->byteArray = $byteArray;
        $this->capacity = count($byteArray);
        $this->limit = $this->capacity;
        $this->position = 0;
    }
    public function _array() {
        return $this->byteArray;
    }
    public function clear() {
        $this->limit = $this->capacity;
        $this->position = 0;
    }
    public function flip() {
        $this->limit = $this->position;
        $this->position = 0;
        return $this;
    }
	public function getByte(){
		if($this->position < $this->limit){
			$byte = $this->byteArray[$this->position];
			$this->position++;
			return $byte;
		}else{
			{Error::getInstance() ->addError( 15  , "Get byte:Out of capability" );} ;
		}
	}
    public function get($length = null) {
        if($length === null) {
            $length = $this->limit - $this->position;
        } elseif($length > $this->remaining()) {
        }
		for($i = 0; $i< $length; $i++){
			$data[] = $this->byteArray[$this->position + $i];
		}
        $this->position += $length;
        return $data;
    }
	public function putByte($byte){
		if($this->position < $this->limit){
			$this->byteArray[$this->position] = $byte;
			$this->position++;
		}else{
			{Error::getInstance() ->addError( 15  , "Put byte:Out of capability" );} ;
		}
	}
    public function position() {
        return $this->position;
    }
    public function put($sourceByteArray) {
		if(count($sourceByteArray) > $this->remaining()) return;
		for($i = 0; $i< count($sourceByteArray); $i++){
			$this->byteArray[$this->position + $i] = $sourceByteArray[$i];
		}
        $this->position  += count($sourceByteArray);
        return $this;
    }
    public function remaining() {
        return $this->limit - $this->position;
    }
    public function rewind() {
        $this->position = 0;
        return $this;
    }
}
?>